package com.cws.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cws.enmu.ConfigKey;
import com.cws.model.SysUser;
import com.cws.sys.Mem;


public class AuthService {

	private static final Logger log = LoggerFactory.getLogger(AuthService.class);
	
	private static final AuthService instance = new AuthService();

	private AuthService() {
	}

	public static AuthService getInstance() {
		return instance;
	}
	
	

	public boolean login(String loginName, String password) {

		List<SysUser> userList = SysUser.dao.getLoginUser(loginName, password);

		if (null != userList && !userList.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	public boolean isvalidToken(String tokenId) {

		Long lastTime = Mem.getTokenInfo().get(tokenId);
		int tokenInvalidTime = Integer.parseInt(Mem.getConfig().getProperty(ConfigKey.tokenInvalidTime.name()));

		if (null == lastTime) {
			return false;
		}

		if ((System.currentTimeMillis() - lastTime) < (tokenInvalidTime * 60 * 1000)) {
			// 更新最后一次请求时间
			Mem.resetTokenTime(tokenId, System.currentTimeMillis());
			return true;
		} else {
			log.debug("the token " + tokenId + " has invalid.");
			Mem.removeToken(tokenId);
			return false;
		}
	}
}
